package cn.workreport.modules.permission.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import cn.workreport.modules.common.vo.PageVO;
import cn.workreport.modules.permission.entity.Permission;
import cn.workreport.modules.permission.enums.PermissionEnum;
import cn.workreport.modules.permission.enums.PermissionModuleEnum;
import cn.workreport.modules.permission.mapper.PermissionMapper;
import cn.workreport.modules.permission.po.PermissionPO;
import cn.workreport.modules.permission.service.IPermissionService;
import cn.workreport.modules.role.entity.Role;
import cn.workreport.modules.role.service.IRoleService;
import cn.workreport.modules.users.entity.UserEntity;
import cn.workreport.util.EnumUtil;
import cn.workreport.util.InitData;
import cn.workreport.util.JsonResult;
import cn.workreport.util.UserChacheFromToken;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务接口实现类
 * </p>
 *
 * @author yyf
 * @since 2022-01-04
 */
@Slf4j
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private InitData initData;

    @Override
    public void wrapEntity(Permission entity) {

    }

    @Override
    public PageVO<Permission> pageEntity(IPage<Permission> page, Wrapper<Permission> queryWrapper) {
        IPage<Permission> pageResult = this.page(page, queryWrapper);
        return new PageVO<>(pageResult);
    }

    @Override
    public Permission getByIdEntity(Integer id) {
        return null;
    }

    @Override
    public JsonResult<?> saveOrUpdateEntity(Permission entity) {
        Permission newEntity = new Permission();

        BeanUtil.copyProperties(
                entity,
                newEntity,
                CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true)
        );

        boolean isSuccess = super.saveOrUpdate(newEntity);
        if (!isSuccess) {
            return JsonResult.fail("操作失败");
        }
        return JsonResult.ok();
    }

    @Override
    public JsonResult<?> removeByIdEntity(Integer id) {
        boolean isSuccess = super.removeById(id);
        if (!isSuccess) {
            return JsonResult.fail();
        }
        return JsonResult.ok();
    }

    @Override
    public JsonResult<?> removeByIdsEntity(List<Integer> ids) {
        for (Integer id : ids) {
            JsonResult<?> jsonResult = removeByIdEntity(id);
            if (!jsonResult.getState().equals(JsonResult.SUCCESS)) {
                return JsonResult.fail();
            }
        }
        return JsonResult.ok();
    }

    /**
     * 根据角色id 查询权限列表
     *
     * @return
     */
    @Override
    public List<Permission> getPermissionListByRoleId(Integer roleId) {
        if (ObjectUtil.isNull(roleId)) {
//            throw new RuntimeException("roleId 不能为 null !");
            return new ArrayList<>();
        }
        LambdaQueryWrapper<Permission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Permission::getRoleId, roleId);
        return list(wrapper);
    }

    @Override
    public JsonResult<?> getPermissionAll() {
        Map<String, Object> data = new HashMap<>();
        // 权限列表
        // 如果是超级管理员，返回所有权限
        UserEntity loginUser = UserChacheFromToken.getUser();
        if (ObjectUtil.isNotEmpty(loginUser.getIsSupperAdmin()) && loginUser.getIsSupperAdmin()) {
            List<Map<String, Object>> permissionList = EnumUtil.getSelectList(PermissionEnum.class);
            data.put("permissionList", permissionList);
        }
        // 如果不是超管
        else {
            // 查出用户的角色名
            List<String> initRoleNameList = Arrays.stream(InitData.InitRoleNameEnum.values())
                    .map(entity -> entity.getRoleName())
                    .collect(Collectors.toList());
            Role userRole = roleService.getById(loginUser.getRoleId());
            List<String> permissions = new ArrayList<>();
            if (ObjectUtil.isNotEmpty(loginUser.getOrgId()) && ObjectUtil.isNotEmpty(userRole)) {
                // 如果是初始化的角色，就返回初始化的权限
                if (initRoleNameList.contains(userRole.getRoleName())) {
                    Optional<Role> initRole = initData.getInitRoleList(loginUser.getOrgId()).stream()
                            .filter(entity -> entity.getRoleName().equals(userRole.getRoleName())).findFirst();
                    if (initRole.isPresent()) {
                        permissions = initRole.get().getPermissions();
                    }
                } else {
                    permissions = userRole.getPermissions();
                }
            }
            if (!permissions.isEmpty()) {
                data.put("permissionList", permissions.stream().map(entity -> {
                    Map<String, String> permissionMap = new HashMap<>();
                    PermissionEnum permissionEnum = PermissionEnum.getEntityByVal(entity);
                    permissionMap.put("label", permissionEnum.getLabel());
                    permissionMap.put("value", permissionEnum.getValue());
                    return permissionMap;
                }));
            }
        }
        // 权限模块
        List<Map<String, Object>> permissionModuleList = EnumUtil.getSelectList(PermissionModuleEnum.class);
        data.put("permissionModuleList", permissionModuleList);
        return JsonResult.ok(data);
    }

    @Override
    public JsonResult<?> saveRolePermission(PermissionPO permissionPO) {
        if (ObjectUtils.isEmpty(permissionPO)) {
            return JsonResult.fail("参数不能为空！");
        }
        if (ObjectUtils.isEmpty(permissionPO.getRoleId())) {
            return JsonResult.fail("参数 roleId 不能为空！");
        }
        if (ObjectUtils.isEmpty(permissionPO.getPermissionList())) {
            return JsonResult.fail("参数 permissionList 不能为空！");
        }
        // 删掉用户之前的所有权限
        LambdaQueryWrapper<Permission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Permission::getRoleId, permissionPO.getRoleId());
        boolean isDeletedSuccess = super.remove(wrapper);
        // 重新保存新的权限
//        if (!isDeletedSuccess) {
//            return JsonResult.fail("保存失败");
//        }
        List<Permission> permissionList = new ArrayList<>();
        for (String permissionValue : permissionPO.getPermissionList()) {
            Permission permissionEntity = new Permission();
            permissionEntity.setRoleId(permissionPO.getRoleId());
            permissionEntity.setPermission(permissionValue);
            permissionList.add(permissionEntity);
        }
        boolean isSuccess = super.saveBatch(permissionList, 20);
        if (!isSuccess) {
            return JsonResult.fail();
        }
        return JsonResult.ok();
    }


}

